<template>
  <div class="usercontiners">
    <div class="casetop">
      <div class="caseback" @click="goback"><van-icon name="arrow-left" /></div>
      <div class="casename">{{ record == 1 ? '图谱' : '病例' }}学习记录</div>
    </div>
    <div class="recordtop">
      <div class="recordtopitem">学习时间</div>
      <div class="recordtopitem">{{ record == 1 ? '图谱' : '病例' }}名称</div>
      <div class="recordtopitem">学习次数</div>
    </div>
    <div
      class="recordbox beautifulScroll"
      @scroll="handleScroll"
      ref="scrollContainer"
      v-if="renderData.length > 0"
    >
      <div class="recorditem" v-for="item in renderData">
        <div class="recordtopitem" v-if="item.startTime">{{
          formatTime(item.startTime)
        }}</div>
        <div class="recordtopitem" v-if="item.createTime">
          {{ item.createTime }}</div
        >

        <div class="recordtopitem">{{
          item.medicineAtlasName || item.caseName
        }}</div>
        <div class="recordtopitem">{{ item.trainNum || item.learnNum }}</div>
      </div>
    </div>
    <div class="recordboxs" v-else>暂无数据</div>
  </div>
</template>

<script lang="ts" setup>
  import { recordlistTp, recordlistlx } from '@/api/outBox';
  import { onBeforeUnmount, reactive, ref } from 'vue';
  import { showSuccessToast, showFailToast } from 'vant';
  import { Pagination } from '@/types/global';
  import { storeToRefs } from 'pinia';
  import { useUserStore } from '@/store';
  const props = defineProps<{
    record: Number;
  }>();
  const emit = defineEmits<{
    (event: 'goback'): void;
    (event: 'customEvent', payload: any): void; // 定义自定义事件
  }>();
  const record = ref(props.record);
  const formatTime = (dateTime: string) => {
    // 转换为 Date 对象
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
    const day = String(date.getDate()).padStart(2, '0'); // 日期补零
    const hours = String(date.getHours()).padStart(2, '0'); // 小时补零
    const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟补零
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  };
  const goback = () => {
    emit('goback');
  };
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const renderData = ref([]); // 渲染的数据列表
  const pagination = reactive({ ...basePagination });
  const userStore = useUserStore();
  const userdata = storeToRefs(userStore);
  const studentId = ref(userdata.studentId.value);
  const fetchData = async (isRefresh = false) => {
    if (record.value == 1) {
      try {
        const res = await recordlistTp({
          pageNum: pagination.current,
          pageSize: pagination.pageSize,
          studentId: studentId.value,
        });

        const newData = res.data.list || [];
        if (isRefresh) {
          renderData.value = newData; // 刷新时替换数据
        } else {
          renderData.value = [...renderData.value, ...newData]; // 加载更多时追加数据
        }
        finished.value = renderData.value.length >= res.data.total; // 检查是否加载完成
      } finally {
        // console.log('加载完成了吗', loading.value);
      }
    } else {
      try {
        const res = await recordlistlx({
          pageNum: pagination.current,
          pageSize: pagination.pageSize,
          studentId: studentId.value,
        });

        const newData = res.data.list || [];
        if (isRefresh) {
          renderData.value = newData; // 刷新时替换数据
        } else {
          renderData.value = [...renderData.value, ...newData]; // 加载更多时追加数据
        }
        finished.value = renderData.value.length >= res.data.total; // 检查是否加载完成
      } finally {
        // console.log('加载完成了吗', loading.value);
      }
    }
  };
  fetchData();
  //  滚动判断
  // 下拉刷新逻辑
  const onRefresh = async () => {
    console.log('触发了刷新');

    pagination.current = 1; // 重置页码
    await fetchData(true); // 刷新数据
    isRefreshing.value = false;
  };

  // 触底加载逻辑
  const onLoadMore = async () => {
    if (finished.value) return;
    pagination.current += 1;
    await fetchData(); // 加载更多数据
    isLoading.value = false;
  };
  const scrollContainer = ref<HTMLElement | null>(null);
  const isRefreshing = ref(false);
  const isLoading = ref(false);
  const finished = ref(false);
  let startY = 0; // 记录触摸开始的位置
  let startX = 0; // 记录触摸开始的横向位置
  let isVerticalScroll = false; // 是否为垂直滚动

  // 下拉刷新处理
  const handleTouchStart = (event: TouchEvent) => {
    startY = event.touches[0].clientY;
    startX = event.touches[0].clientX;
    isVerticalScroll = false; // 重置滚动方向
  };

  let debounceTimeout: ReturnType<typeof setTimeout>;

  const handleTouchMove = (event: TouchEvent) => {
    const moveY = event.touches[0].clientY;
    const moveX = event.touches[0].clientX;
    const diffY = Math.abs(moveY - startY);
    const diffX = Math.abs(moveX - startX);

    // 判断是否为垂直滚动（如果垂直位移大于水平位移）
    if (!isVerticalScroll && diffY > diffX) {
      isVerticalScroll = true;
    }

    if (!isVerticalScroll) {
      // 如果不是垂直滚动，直接返回
      return;
    }

    if (scrollContainer.value && scrollContainer.value.scrollTop > 0) {
      return; // 如果不是在顶部，则不处理下拉刷新
    }

    clearTimeout(debounceTimeout); // 清除上一次的定时器
    debounceTimeout = setTimeout(() => {
      if (moveY - startY > 50 && !isRefreshing.value) {
        // 判断下拉超过50px
        isRefreshing.value = true;
        onRefresh();
      }
    }, 300); // 防抖：300ms
  };

  const handleTouchEnd = () => {
    startY = 0; // 清除触摸开始位置
    startX = 0; // 清除横向触摸开始位置
    isVerticalScroll = false; // 重置方向标志
    if (isRefreshing.value) {
      console.log('刷新已完成');
    }
  };

  // 触底加载处理
  let lastScrollTime = 0;

  const handleScroll = (event: Event) => {
    if (isRefreshing.value) return; // 正在刷新时，不触发触底加载
    const now = Date.now();
    if (now - lastScrollTime > 300) {
      lastScrollTime = now;
      const container = event.target as HTMLElement;
      if (
        container.scrollTop + container.clientHeight >=
          container.scrollHeight - 100 &&
        !isLoading.value
      ) {
        if (finished.value) return;
        isLoading.value = true;
        console.log('触底了');
        onLoadMore();
      }
    }
  };

  // 绑定触摸事件
  const bindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.addEventListener('touchstart', handleTouchStart);
      scrollContainer.value.addEventListener('touchmove', handleTouchMove);
      scrollContainer.value.addEventListener('touchend', handleTouchEnd);
    }
  };

  // 清除触摸事件
  const unbindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.removeEventListener('touchstart', handleTouchStart);
      scrollContainer.value.removeEventListener('touchmove', handleTouchMove);
      scrollContainer.value.removeEventListener('touchend', handleTouchEnd);
    }
  };

  // 生命周期钩子：组件卸载时清除事件
  onBeforeUnmount(() => {
    unbindTouchEvents();
  });
  // 滚动判断逻辑完成
</script>

<style scoped>
  .recordbox {
    height: 100%;
    background-color: #f1f1f1;
    text-align: center;
    overflow-y: auto;
    padding-bottom: 100px;
  }
  .recordboxs {
    height: 100%;
    width: 100%;
    background-color: #f1f1f1;
    text-align: center;
    overflow-y: auto;

    font-size: 30px;
    padding-top: 20px;
  }

  .recorditem {
    width: 750px;
    height: 70px;
    background: #f6f6f6;
    display: flex;
  }
  /* 奇数项背景色 */
  .recorditem:nth-child(odd) {
    background: #f6f6f6;
  }

  /* 偶数项背景色 */
  .recorditem:nth-child(even) {
    background: #ffffff; /* 白色 */
  }
  .recordtop {
    width: 750px;
    height: 70px;
    background-color: #fff;

    display: flex;
    align-items: center;
    justify-content: center;
  }
  .recordtopitem {
    width: 250px;
    height: 70px;
    line-height: 70px;
    color: #666666;
    font-size: 26px;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .usercontiners {
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg, #5f6d7c 0%, #fff 25%);
    position: absolute;
    top: 0px;
    left: 0px;
  }

  .casetop {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100px;
    font-size: 32px;
    color: #ffff;
    position: relative;
    top: 0;
    left: 0;
  }
  .caseback {
    font-size: 36px;
    color: #ffff;
    position: absolute;
    left: 20px;
  }
</style>
